<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Backend_UserController
 *
 * @author Eugene
 */
class Backend_UserController extends Zend_Controller_Action
{

	/**
	 * @var Application_Model_Mapper_User
	 */
	protected $_mapper;

	/**
	 *
	 * @return Application_Model_Mapper_User
	 */
	public function getMapper()
	{
		if (null === $this->_mapper) {
			$this->_mapper = new Application_Model_Mapper_User;
		}

		return $this->_mapper;
	}

	public function init()
	{
		$ajaxContext = $this->_helper->getHelper('AjaxContext');

		$ajaxContext->addActionContext('index', 'html')
				->addActionContext('create', 'html')
				->addActionContext('update', 'html')
				->initContext();
	}

	/**
	 *
	 * @return void
	 */
	public function indexAction()
	{
		$messages = $this->_helper->flashMessenger->getMessages();
		$messages = array_flip($messages);

		$this->view->messages = $messages;
		$this->view->form = new Backend_Form_User_Create;
		$this->view->entries = $this->getMapper()->fetchAll();
	}

	/**
	 *
	 * @return void
	 */
	public function createAction()
	{
		$form = new Backend_Form_User_Create;

		if ($this->getRequest()->isPost()) {
			if ($form->isValid($this->getRequest()->getPost())) {
				$model = new Application_Model_User($form->getValues());
				$this->getMapper()->save($model);

				$this->_helper->flashMessenger('created');
				return $this->_helper->redirector('index');
			}
		}

		$this->view->form = $form;
	}

	/**
	 *
	 * @return void
	 */
	public function updateAction()
	{
		$model = new Application_Model_User;
		$this->getMapper()->fetchById($this->getRequest()->getParam('id'), $model);

		$form = new Backend_Form_User_Update(array(
					'userId' => $this->getRequest()->getParam('id')
				));

		if ($this->getRequest()->isPost()) {
			if ($form->isValid($this->getRequest()->getPost())) {
				$model->setOptions($form->getValues());
				$this->getMapper()->save($model);

				$this->_helper->flashMessenger('updated');
				return $this->_helper->redirector('index');
			}
		} else {
			$form->populate($model->toArray());
		}

		$this->view->form = $form;
	}

	/**
	 *
	 * @return void
	 */
	public function deleteAction()
	{
		$this->getMapper()->delete($this->getRequest()->getParam('id'));

		$this->_helper->flashMessenger('deleted');
		return $this->_helper->redirector('index');
	}

	public function enableAction()
	{

	}

}